{include file="public/header" /}



<div class="page">
    <div class="fixed-bar">
        <div class="item-title">
            <div class="subject">
                <h3>数据签名</h3>
                <h5></h5>
            </div>
            {include file="public/admin_items" /}
        </div>
    </div>

    <div class="block-area">
        <table class="sc-default-table">
            <thead>
            <tr class="thead">
                <th width="200">订单号</th>
                <th>签名状态</th>
            </tr>
            </thead>
            <tbody class="list-container">
            </tbody>
        </table>
    </div>
</div>
<script type="text/javascript" src="{$Think.PLUGINS_SITE_ROOT}/chinaport/client.js?d=2018-12-19_16:00:00"></script>
<script>
    function signDataAsPEM(str) {
        var password = 'f1234567';
        return new Promise(function (resolve, reject) {
	        EportClient.isInstalledTest(EportClient.cusSpcSignDataAsPEM, str, password, function (msg, msgJson) {
	        	if(msg.Result) {
			        resolve(JSON.stringify(msg.Data));
                } else {
                    reject(msg.Error.join(','));
                }
	        });
        });
    }

    // 获取待签名的订单列表
    function getOrderList() {
        $.get("{:url('chinaport/orderlist')}", function (result) {
	        $('.list-container').html('');

	        if(result.msg.length == 0) {
		        $('.list-container').html('<tr><td class="order_no">暂无待签名数据</td><td class="upload_state">'+new Date().toTimeString()+'</td></tr>');
            }

            result.msg.forEach(function (item) {
                let rowObj = $('<tr><td class="order_no">'+item.order_no+'</td><td class="upload_state">未签名</td></tr>');
                rowObj.appendTo($('.list-container'));
	            item.rowObj = rowObj;
            });

	        function sign() {
	        	console.log(result.msg);
	        	if(result.msg.length) {
			        let item = result.msg.shift();

			        var serviceTime = (new Date()).getTime();
			        item.sign_data.push('"serviceTime":"' + serviceTime + '"');
			        console.log(item.sign_data.join('||'));
			        signDataAsPEM(item.sign_data.join('||')).then(function (sign_data) {
				        $.post('{:url("Chinaport/save")}', {
					        id: item.id,
					        sign_data: sign_data,
					        service_time: serviceTime
				        }, function () {
					        item.rowObj.find('.upload_state').html('已签名');

					        setTimeout(function () {
                                sign();
					        }, 3000)
				        });
			        }).catch(function (msg) {
				        layer.msg(msg);
				        setTimeout(function () {
					        sign();
				        }, 10000);
			        });
                } else {
			        setTimeout(function () {
				        getOrderList();
			        }, 10 * 1000);
                }
	        }

	        sign();
        });
    }

    getOrderList();
</script>


